import json
import logging
import tornado.web
import tornado.websocket
from tornado import gen
from myredis.myconnect import r


chatgroup = {}  # 存储连接用户名和对应的websockethandler对象


class ChatSocketHandler(tornado.websocket.WebSocketHandler):

    def open(self,groupname):
        logging.info('websocket opened')
        self.fromuser = ''#self.get_argument('from')
        self.groupname = groupname
        chatgroup[groupname] = self  # 存入建立连接的用户

    def on_message(self, message):
        parsed = tornado.escape.json_decode(message)  # 解析消息为json
        self.fromuser = parsed['from_user']  # 信息发送方
        self.touser = parsed['to_user']  # 信息接收方
        logging.info('%s send msg to %s' % (self.fromuser, self.touser))

        print(parsed)
        if self.touser in chatgroup.keys():#如果接受者已经建立了websocket连接
            chatgroup[self.groupname][self.touser].write_message(message)  # 发送消息tornado.escape.json_encode(parsed)
        else:
            unrecvkey='chat||'+str(self.touser)+'||notrecv||'+self.groupname
            self.savemessage(unrecvkey, json.dumps(message))

    @gen.coroutine
    def savemessage(self, groupname, message):
        try:
            r.lpush(groupname, message)
        except Exception as e:
            logging.error(e)

    def on_close(self):
        logging.info('%s socket closed'%self.fromuser)
        if self.fromuser in chatgroup.keys():
            del chatgroup[self.fromuser]

    def check_origin(self, origin):
        return True


